<?php
/**
 * Created by PhpStorm.
 * User: dust2
 * Date: 14-12-1
 * Time: 下午3:23
 */

/**
 * Class CookieCart
 * 基于Cookie的商品购物车操作
 * 暂时不做序列化cookie数据
 */

class CookieCart
{
    /**
     * @param $product_id
     * @param $parameters
     * @return \Symfony\Component\HttpFoundation\Cookie
     * 添加商品至cookie
     */
    public static function refreshProduct($product_id, $parameters)
    {
        $cookieCart = Cookie::get(self::$cookieName);
        $cookieCart[self::$userId][$product_id] = $parameters;
        return Cookie::make(self::$cookieName, $cookieCart, self::$minutes);
    }

    /**
     * @return mixed
     * 从cookie中获取商品
     */
    public static function getProducts()
    {
        $products = Cookie::get(self::$cookieName)[self::$userId];
        return $products;
    }

    /**
     * @param $product_id
     * @return \Symfony\Component\HttpFoundation\Cookie
     * 从cookie中删除商品
     */
    public static function deleteProduct($product_id)
    {
        $original = Cookie::get(self::$cookieName);
        unset($original[self::$userId][$product_id]);

        //这里cookie有效期将得到刷新，即时间重新计时
        return Cookie::make(self::$cookieName, $original, self::$minutes);
    }

    /**
     * 从cookie中删除所有商品
     * @return \Symfony\Component\HttpFoundation\Cookie
     */
    public static function deleteProducts()
    {
        return Cookie::make(self::$cookieName, null, 0);
    }

    /**
     * @return CookieCart
     * 获取单件
     */
    public static function start()
    {
        self::$userId = Auth::user()['id'];
    }

    /**
     * 购物车相关信息（用户id、商品数量）
     * cookie格式
     * cookieCart = [
     *     user_id => [
     *         product_id => [
     *             'count' => 2;
     *         ]
     *     ]
     * ];
     * 如：
     * cookieCart = [
     *     1 => [
     *         2 => [
     *             'count' => 2
     *         ]
     *     ]
     * ];
     */
    protected  static $cookieName = 'cookieCart';
    protected  static $userId;
    protected  static $minutes = 10080; //cookie有效时间7天(10080分钟)
} 